package com.bytedance.improvingroad.utils

import android.graphics.Canvas
import android.util.Log
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.bytedance.improvingroad.adapter.SlideCardAdapter
import com.bytedance.improvingroad.model.CardConfig
import com.bytedance.improvingroad.model.SlideCardBean
import kotlin.math.sqrt

/**
 * Created by chenxiong
 * date 11/17/21
 */
class SlideCallback(
    private val adapter: SlideCardAdapter,
    private val mDatas: MutableList<SlideCardBean>
) : ItemTouchHelper.SimpleCallback(0, 15) {
    override fun onMove(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder,
        target: RecyclerView.ViewHolder
    ): Boolean {
        return false
    }

    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
        val remove = mDatas.removeAt(viewHolder.layoutPosition)
        mDatas.add(0, remove)
        adapter.notifyDataSetChanged()
    }

    override fun onChildDraw(
        c: Canvas,
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder,
        dX: Float,
        dY: Float,
        actionState: Int,
        isCurrentlyActive: Boolean
    ) {
        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
        val maxDistance = recyclerView.width * 0.5f
        val distance = sqrt((dX * dX + dY * dY).toDouble())
        var fraction = distance / maxDistance
        if (fraction > 1) {
            fraction = 1.0
        }
        val itemCount = recyclerView.childCount
        for (i in 0 until itemCount) {
            val view = recyclerView.getChildAt(i)
            val level = itemCount - i - 1
            Log.e("cx","当前孩子：$i")
            if (level > 0) {
                if (level < CardConfig.MAX_SHOW_COUNT - 1) {
                    view.translationY =
                        (CardConfig.TRANS_Y_GAP * level - fraction * CardConfig.TRANS_Y_GAP).toFloat()
                    view.scaleX =
                        (1 - CardConfig.SCALE_GAP * level + fraction * CardConfig.SCALE_GAP).toFloat()
                    view.scaleY =
                        (1 - CardConfig.SCALE_GAP * level + fraction * CardConfig.SCALE_GAP).toFloat()
                }
            }
        }
    }

    override fun getAnimationDuration(
        recyclerView: RecyclerView,
        animationType: Int,
        animateDx: Float,
        animateDy: Float
    ): Long {
        return 500
    }
}